package thread;

public class Bank extends Thread {
    private Card card;//信用卡额度
    private Integer get;//取款额度

    public Bank(Card card) {//构造函数
        this.card = card;
    }

    public Integer getGet() {
        return get;
    }

    public void setGet(Integer get) {
        this.get = get;
    }
    public void take(){
        synchronized (card){//给Card()方法加锁
            if (card.getMoney()>=get){
                card.setMoney(card.getMoney()-get);
                System.out.println("成功取款:"+get);
            }
            else{
                System.out.println("余额不足！");
        }
        }
    }


    @Override
    public void run() {
        if (get>0){
            take();
        }
    }
    public static void main(String[] agrs){
        Card card=new Card(5000);
        Bank bank1=new Bank(card);
        Bank bank2=new Bank(card);
        bank1.setGet(4000);
        bank1.start();
        bank2.setGet(2000);
        bank2.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("余额："+card.getMoney());
    }
}
class Card{
    private int money;

    public Card(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}
